import router from "@/router"
import { useLoginUserStore } from "@/stores/user"
import { message } from "ant-design-vue"
import AccessEnum from "./access/accessEnum"

//是否为首次登录用户
let isFirstLoginUser = true

/**
 * 全局信息校验
 */
router.beforeEach(async(to, from, next) => {
  const loginUserStore = useLoginUserStore()
  let loginUser = loginUserStore.loginUser

  //确保页面刷新 首次加载时 等后端返回用户信息再校验身份权限
  if(isFirstLoginUser){
    await loginUserStore.fetchLoginUser()
    loginUser = loginUserStore.loginUser
    isFirstLoginUser = false
  }
  const toUrl = to.fullPath
  if(toUrl.startsWith("/admin")){
    if(!loginUser||loginUser.userRole!==AccessEnum.ADMIN){
      message.error("无权限访问")
      next(`"/user/login?redirect=${to.fullPath}"`)
      return
    }
  }
  next()
})
